package studio.raptor.extractor.segment.task;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import studio.raptor.extractor.common.util.Pair;
import studio.raptor.extractor.segment.constant.EventKindConstant;
import studio.raptor.extractor.segment.constant.JsonElementName;
import studio.raptor.extractor.segment.entity.BuildJsonResult;
import studio.raptor.extractor.segment.entity.EventDataInfo;
import studio.raptor.extractor.segment.entity.EventMeta;
import studio.raptor.hub.in.server.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Created by liuyong8 on 2017/7/28.
 */
public class NodeMsgBuildingTask implements Callable<BuildJsonResult> {
    private static final Logger log = LoggerFactory.getLogger(NodeMsgBuildingTask.class);
    private EventDataInfo eventDataInfo;

    public NodeMsgBuildingTask(EventDataInfo eventDataInfo) {
        this.eventDataInfo = eventDataInfo;
    }

    @Override
    public BuildJsonResult call() throws Exception {
        List<Pair<String,String>> nodeDatas = eventDataInfo.getNodes();
        Map<String,String> rootMap = new HashMap<String,String>();

        if (nodeDatas == null) {
            return buildResult(eventDataInfo.getEventMeta(),null);
        }
        String json = "";
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (Pair<String,String> nodeData : nodeDatas) {
            String jsonNodeName = nodeData.getKey();
            String nodeValue = nodeData.getValue();
            if (nodeValue.trim().startsWith("{") || nodeValue.trim().startsWith("[")){
                sb.append("\"" + jsonNodeName + "\"" + ":" + nodeValue + ",");
            }else {
                sb.append("\"" + jsonNodeName + "\"" + ":{" + nodeValue + "},");
            }
            rootMap.put(jsonNodeName,nodeValue);
        }

        json = sb.toString().substring(0,sb.toString().length()-1) + "}";
        return buildResult(eventDataInfo.getEventMeta(),json);
    }

    private BuildJsonResult buildResult(EventMeta eventMeta,String json){
        BuildJsonResult buildJsonResult = new BuildJsonResult();
        buildJsonResult.setMetaId(eventMeta.getMetaId());
        buildJsonResult.setEventMeta(eventMeta);
        buildJsonResult.setJson(json);
        return buildJsonResult;
    }
}
